package com.mathmu.fetion.protocol;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.mathmu.IncompetentPlatformException;

public class Config {
	static public byte[] generateConfigurationXML(Account user)
	{
		try {
			final Document doc = DocumentBuilderFactory.newInstance()
										.newDocumentBuilder().newDocument();
			
			final Element config = doc.createElement("config");
			doc.appendChild(config);
			
			final Element userElem = doc.createElement("user");
			userElem.setAttribute("mobile-no", user.mobileNumber);
			config.appendChild(userElem);
			
			final Element clientElem = doc.createElement("client");
			clientElem.setAttribute("type", "PC");
			// TODO: can we define our own version and platform info?
			clientElem.setAttribute("version", "3.6.1900");
			clientElem.setAttribute("platform", "W5.1");
			config.appendChild(clientElem);
			
			final Element serversElem = doc.createElement("servers");
			serversElem.setAttribute("version", user.configServersVersion);
			config.appendChild(serversElem);
			
			final Element parametersElem = doc.createElement("parameters");
			parametersElem.setAttribute("version", "0");
			config.appendChild(parametersElem);
			
			final Element hintsElem = doc.createElement("hints");
			hintsElem.setAttribute("version", user.configServersVersion);
			config.appendChild(hintsElem);
			
			doc.setXmlVersion("1.0");
			
			Source source = new DOMSource(doc);
			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
			Result result = new StreamResult(buffer);
			TransformerFactory.newInstance()
				.newTransformer().transform(source, result);
			return buffer.toByteArray();
		} catch (DOMException e) {
			throw new IncompetentPlatformException(e);
		} catch (ParserConfigurationException e) {
			throw new IncompetentPlatformException(e);
		} catch (TransformerException e) {
			throw new IncompetentPlatformException(e);
		}
	}
	
	public static void downloadConfiguration(Account user) 
			throws IOException {
		final String host = "nav.fetion.com.cn";

		try {
			final byte[] body = generateConfigurationXML(user);
			URL url = new URL(String.format("http://%s/nav/getsystemconfig.aspx", 
												host));
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("User-Agent", "IIC2.0/PC 2.6.1900");
			conn.setRequestProperty("Content-Type", "text/xml");
			conn.setRequestProperty("Content-Length", 
										String.valueOf(body.length));
			conn.setDoOutput(true);
			conn.getOutputStream().write(body);

			byte[] content = new byte[conn.getContentLength()];
			final int bytesRead = conn.getInputStream().read(content, 0, 
															content.length);
			assert bytesRead == content.length;
			
			BufferedReader br = new BufferedReader(
					new InputStreamReader(new ByteArrayInputStream(content), 
											"UTF-8"));
			while (true) {
				String line = br.readLine();
				if (line == null) {
					break;
				}
				System.out.println(line);
			}
			// refresh_configuration_xml(res , path , user);
		} catch (UnsupportedEncodingException e) {
			throw new IncompetentPlatformException(e);
		} catch (MalformedURLException e) {
			throw new IncompetentPlatformException(e);
		} catch (ProtocolException e) {
			throw new IncompetentPlatformException(e);
		}
	}
}
